package com.haha.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.haha.demo.dao.UserDao;
import com.haha.demo.entity.User;
import com.haha.demo.service.intf.UserService;
import com.haha.demo.vo.PageVo;
import com.haha.demo.vo.R;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserDao dao;

    @Override
    public R all() {
        return R.ok(dao.selectList(null));
    }

    @Override
    public PageVo querPage(int page, int limit) {
        PageHelper.startPage(page,limit);
        PageInfo<User> pageInfo = new PageInfo<>(dao.selectList(null));
        return PageVo.ok(pageInfo.getTotal(),pageInfo.getList());
    }

    @Override
    public R login(String name, String pwd, HttpSession session) {
        if (StringUtils.hasLength(name) && StringUtils.hasLength(pwd)){
            User user = dao.selectOne(new QueryWrapper<User>().eq("uname",name));
            if (user != null){
                if (user.getUpwd().equals(pwd)){
                    //密码一致 登录成功
                    session.setAttribute("user",user);
                    return R.ok("亲，登录成功！！");
                }
            }
        }
        return R.fail("亲，登录失败！！");
    }

    @Override
    public R update(User user) {
        if (user!=null){
            if (dao.update(user.getUname(), user.getUpwd(), user.getUtype(), user.getUmemo(), user.getUcode())>0){
                return R.ok();
            }
        }
        return R.fail();
    }

    @Override
    public R delete(int id) {
        if (id >0){
            if (dao.delete(id)>0){
                return R.ok();
            }
        }
        return R.fail();
    }

    @Override
    public R add(User user) {
        if (user!=null){
            if (dao.insert(user)>0){
                return R.ok();
            }
        }
        return R.fail();
    }

}
